import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { RootState } from "@/stores";
import { router } from "expo-router";
import { toast } from "gluestack-ui";

const tagTypes = ["User", "Product"]; // 需要缓存的数据

// 请求拦截
const requestInterceptors = (
  headers: Headers,
  { getState }: { getState: () => RootState }
) => {
  const token = (getState() as RootState).user.token;
  if (token) {
    headers.set("authorization", `Bearer ${token}`);
  }
  return headers;
};

// 响应拦截
const responseInterceptors = async (result: any) => {
  if (result.error?.status === 401) {
    router.replace("/(views)/auth/login");
  }
  if (result.error?.data?.message) {
    toast.error(result.error?.data?.message);
  }
  return result;
};

const baseQuery = fetchBaseQuery({
  baseUrl: "https://test-loan.paypaya.com",
  prepareHeaders: requestInterceptors,
});

const baseQueryWithAuth = async (args: any, api: any, extraOptions: any) => {
  const result = await baseQuery(args, api, extraOptions);
  return responseInterceptors(result);
};

export const baseApi = createApi({
  reducerPath: "uapi",
  baseQuery: baseQueryWithAuth,
  tagTypes: tagTypes,
  endpoints: () => ({}),
});
